<template>
  <div class="file-manager">
    <!-- 第一层：主要统计卡片 -->
    <div class="main-stats">
      <div class="stat-box upload-box">
        <div class="stat-icon">
          <FolderOutlined />
        </div>
        <div class="stat-content">
          <div class="stat-title">今日上传</div>
          <div class="stat-value">{{ todayUploadCount }}</div>
        </div>
      </div>
      
      <div class="stat-box audit-box">
        <div class="stat-icon">
          <CheckCircleOutlined />
        </div>
        <div class="stat-content">
          <div class="stat-title">已审核</div>
          <div class="stat-value">{{ auditedCount }}</div>
        </div>
      </div>
      
      <div class="stat-box pending-box">
        <div class="stat-icon">
          <ClockCircleOutlined />
        </div>
        <div class="stat-content">
          <div class="stat-title">未审核</div>
          <div class="stat-value">{{ pendingAuditCount }}</div>
        </div>
      </div>
    </div>

    <!-- 第二层：学习资料管理 -->
    <div class="material-management">
      <div class="material-header">
        <h2><BookOutlined /> 学习资料管理</h2>
        
        <!-- 筛选和搜索 -->
        <div class="filter-section">
          <div class="filter-row">
            <div class="filter-item">
              <label>审核状态：</label>
              <a-select 
                v-model:value="filterParams.auditStatus" 
                placeholder="请选择审核状态"
                style="width: 150px"
                @change="handleFilterChange"
                allowClear
              >
                <a-select-option :value="0">待审核</a-select-option>
                <a-select-option :value="1">通过</a-select-option>
                <a-select-option :value="2">拒绝</a-select-option>
              </a-select>
            </div>
            
            <div class="filter-item">
              <label>关键词：</label>
              <a-input 
                v-model:value="filterParams.keyword"
                placeholder="请输入文件名或关键词"
                style="width: 200px"
                @pressEnter="handleSearch"
                allowClear
              >
                <template #suffix>
                  <a-button type="text" @click="handleSearch">
                    <SearchOutlined />
                  </a-button>
                </template>
              </a-input>
            </div>
            
            <a-button type="primary" @click="handleSearch">搜索</a-button>
            <a-button @click="handleReset">重置</a-button>
          </div>
        </div>

        <!-- 批量操作 -->
        <div class="batch-actions" v-if="selectedRowKeys.length > 0">
          <span>已选择 {{ selectedRowKeys.length }} 项</span>
          <a-button type="primary" @click="handleBatchAudit(1)">
            <CheckOutlined /> 批量通过
          </a-button>
          <a-button danger @click="handleBatchAudit(2)">
            <CloseOutlined /> 批量拒绝
          </a-button>
        </div>
      </div>

      <!-- 学习资料列表 -->
      <div class="material-list">
        <div v-if="materialLoading" class="loading">
          <a-spin size="large" />
          <p>正在加载学习资料...</p>
        </div>
        <div v-else-if="materialError" class="error">
          <a-alert type="error" :message="materialError" show-icon />
        </div>
        <div v-else>
          <a-table 
            :data-source="materialList" 
            :columns="materialColumns" 
            :pagination="paginationConfig"
            :loading="materialLoading"
            @change="handleTableChange"
            row-key="id"
            bordered
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
              getCheckboxProps: (record: any) => ({
                disabled: record.auditStatus === 1, // 已通过的不能再次审核
              }),
            }"
          >
            <!-- 审核状态 -->
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'auditStatus'">
                <a-tag :color="getAuditStatusColor(record.auditStatus)">
                  {{ record.auditStatusText }}
                </a-tag>
              </template>
              
              <!-- 时间格式化 -->
              <template v-if="column.key === 'createTime'">
                {{ formatDateTime(record.createTime) }}
              </template>
              <template v-if="column.key === 'updateTime'">
                {{ formatDateTime(record.updateTime) }}
              </template>
              
              <!-- 操作按钮 -->
              <template v-if="column.key === 'actions'">
                <div class="action-buttons">
                  <a-button type="link" @click="handleView(record)">
                    <EyeOutlined /> 查看
                  </a-button>
                  <a-button type="link" @click="handleAuditStatusUpdate(record)">
                    <EditOutlined /> 通过
                  </a-button>
                  <a-button type="link" danger @click="handleDelete(record)">
                    <DeleteOutlined /> 删除
                  </a-button>
                </div>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive, h } from 'vue'
import { 
  getDailyUploadStats, 
  getAuditStats, 
  getLearningMaterialList, 
  deleteLearningMaterial,
  auditLearningMaterial,
  batchAuditLearningMaterial,
  type LearningMaterialListParams,
  type AuditMaterialParams,
  type BatchAuditMaterialParams,
  type BatchMaterialAuditDTO,
  type MaterialAuditDTO
} from '@/api/file'
import { message, Modal } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import {
  FolderOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  BookOutlined,
  SearchOutlined,
  FileTextOutlined,
  EyeOutlined,
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  CheckOutlined,
  CloseOutlined
} from '@ant-design/icons-vue'

// 用户信息
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const error = ref('')
const uploadStats = ref<Array<{name: string, count: number}>>([])

const auditLoading = ref(false)
const auditError = ref('')
const auditStats = ref<Array<{name: string, count: number}>>([])

const materialLoading = ref(false)
const materialError = ref('')
const materialList = ref<any[]>([])

// 筛选参数
const filterParams = reactive<LearningMaterialListParams>({
  current: 1,
  size: 10,
  auditStatus: undefined,
  keyword: '',
  orderBy: 'time'
})

// 分页配置
const paginationConfig = computed(() => ({
  current: filterParams.current,
  pageSize: filterParams.size,
  total: materialTotal.value,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
  pageSizeOptions: ['10', '20', '50', '100']
}))

const materialTotal = ref(0)

// 表格选择相关
const selectedRowKeys = ref<number[]>([])
const selectedRows = ref<any[]>([])

// 表格列配置
const materialColumns = [
  {
    title: '文件名',
    dataIndex: 'title',
    key: 'title',
    width: 100,
    ellipsis: true
  },
  {
    title: '学科',
    dataIndex: 'subjectType',
    key: 'subjectType',
    width: 140
  },
  {
    title: '审核状态',
    dataIndex: 'auditStatusText',
    key: 'auditStatus',
    width: 100,
    align: 'center' as const
  },
  {
    title: '上传时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 160,
    align: 'center' as const
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    width: 160,
    align: 'center' as const
  },
  {
    title: '下载次数',
    dataIndex: 'downloadCount',
    key: 'downloadCount',
    width: 70,
    align: 'center' as const
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center' as const,
    fixed: 'right' as const
  }
]


// 计算属性
const todayUploadCount = computed(() => {
  if (!Array.isArray(uploadStats.value)) return 0
  const today = new Date().toISOString().split('T')[0]
  const todayData = uploadStats.value.find(item => item.name === today)
  return todayData ? todayData.count : 0
})

const pendingAuditCount = computed(() => {
  if (!Array.isArray(auditStats.value)) return 0
  const pendingItem = auditStats.value.find(item => item.name === '待审核')
  return pendingItem ? pendingItem.count : 0
})

const auditedCount = computed(() => {
  if (!Array.isArray(auditStats.value)) return 0
  const auditedItem = auditStats.value.find(item => item.name === '审核通过')
  return auditedItem ? auditedItem.count : 0
})


// 获取每日上传统计数据
const fetchUploadStats = async () => {
  try {
    loading.value = true
    error.value = ''
    const response = await getDailyUploadStats()
    uploadStats.value = response.data || []
    
  } catch (err: any) {
    error.value = err.message || '获取数据失败'
    
  } finally {
    loading.value = false
  }
}

// 获取审核统计数据
const fetchAuditStats = async () => {
  try {
    auditLoading.value = true
    auditError.value = ''
    const response = await getAuditStats()
    auditStats.value = response.data.data || response.data || []
    
  } catch (err: any) {
    auditError.value = err.message || '获取审核统计失败'
    
  } finally {
    auditLoading.value = false
  }
}

// 工具函数
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getAuditStatusColor = (status: number) => {
  switch (status) {
    case 0: return 'orange'  // 待审核
    case 1: return 'green'   // 通过
    case 2: return 'red'     // 拒绝
    default: return 'default'
  }
}

// 获取学习资料列表
const fetchMaterialList = async (params?: LearningMaterialListParams) => {
  try {
    materialLoading.value = true
    materialError.value = '' 
    
    const queryParams = { ...filterParams, ...params }
    const response = await getLearningMaterialList(queryParams)
    console.log('完整响应:', response)
    
    // 确保数据结构正确
    let records = []
    let total = 0 
    // 根据API响应结构解析数据
    // 响应格式: { code: 200, data: { records: [...], total: 0 }, message: "Success" }
    if (response.data && response.data.data && response.data.data.records) {
      records = response.data.data.records
      total = response.data.data.total || 0
     
    } else {
      
      records = []
      total = 0
    }
    
    materialList.value = records
    materialTotal.value = total
  } catch (err: any) {
    materialError.value = err.message || '获取学习资料列表失败'
    materialList.value = [] // 确保错误时也是数组
    materialTotal.value = 0
    
  } finally {
    materialLoading.value = false
  }
}

// 事件处理函数
const handleFilterChange = () => {
  filterParams.current = 1
  fetchMaterialList()
}

const handleSearch = () => {
  filterParams.current = 1
  fetchMaterialList()
}

const handleReset = () => {
  filterParams.auditStatus = undefined
  filterParams.keyword = ''
  filterParams.current = 1
  fetchMaterialList()
}

const handleTableChange = (pagination: any) => {
  filterParams.current = pagination.current
  filterParams.size = pagination.pageSize
  fetchMaterialList()
}

const handleView = (record: any) => {
  if (record.filePath) {
    window.open(record.filePath, '_blank')
  } else {
    message.warning('文件路径不存在')
  }
}

// 表格选择变化
const onSelectChange = (keys: number[], rows: any[]) => {
  selectedRowKeys.value = keys
  selectedRows.value = rows
  console.log('选择变化:', { keys, rows })
}

// 单个审核状态更新
const handleAuditStatusUpdate = (record: any) => {
  Modal.confirm({
    title: '审核操作',
    icon: () => h(ExclamationCircleOutlined),
    content: () => h('div', [
      h('p', `正在审核: ${record.title}`),
      h('div', { style: 'margin-top: 16px; display: flex; gap: 12px; justify-content: center' }, [
        h('button', {
          class: 'ant-btn ant-btn-primary',
          onClick: () => {
            handleSingleAudit(record.id, 1, "审核通过")
          }
        }, [h(CheckOutlined), ' 通过']),
        h('button', {
          class: 'ant-btn ant-btn-danger',
          onClick: () => {
            Modal.destroyAll() // 先关闭当前弹窗
            showRejectModal(record.id)
          }
        }, [h(CloseOutlined), ' 不通过'])
      ])
    ]),    
    footer: null, // 移除底部按钮
    centered: true,
    width: 400,
    closable: true, // 显示右上角关闭按钮
    maskClosable: true, // 点击遮罩层关闭
  })
}

// 显示拒绝原因输入框
const showRejectModal = (materialId: number) => {
  let rejectReason = ''
  
  Modal.confirm({
    title: '拒绝审核',
    icon: () => h(ExclamationCircleOutlined, { style: { color: '#ff4d4f' } }),
    content: () => h('div', [
      h('p', '请输入拒绝原因:'),
      h('textarea', {
        class: 'ant-input',
        style: 'width: 100%; min-height: 80px; margin-top: 8px',
        placeholder: '请详细说明拒绝原因...',
        onInput: (e: any) => rejectReason = e.target.value
      })
    ]),
    okText: '确认拒绝',
    okType: 'danger',
    cancelText: '取消',
    centered: true,
    onOk: () => handleSingleAudit(materialId, 2, rejectReason || '不符合要求')
  })
}

// 单个审核
const handleSingleAudit = async (materialId: number, auditStatus: number, auditReason: string) => {
  try {
    // 获取管理员ID
    console.log(userStore);
    
    const adminId = userStore.userInfo?.id
    if (!adminId) {
      message.error('获取管理员信息失败，请重新登录')
      return
    }
  const data: AuditMaterialParams = {
    adminId,
    materialAuditDTO: {
      materialId,
      auditStatus,
      auditReason
    }
  }
    console.log(data);
   const res = await auditLearningMaterial(data)
   console.log(res);
   
   // 检查响应结果
   if (res.data.code === 200) {
     message.success('审核成功!' )
   }
    
   await fetchMaterialList()
    Modal.destroyAll() // 关闭所有弹窗
  } catch (error: any) {
    console.error('审核失败:', error)
    message.error('审核失败，请重试')
  }
}

// 批量审核
const handleBatchAudit = (auditStatus: number) => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要审核的资料')
    return
  }

  const statusText = auditStatus === 1 ? '通过' : '拒绝'
  
  if (auditStatus === 2) {
    // 批量拒绝需要输入原因
    showBatchRejectModal()
  } else {
    // 批量通过
    Modal.confirm({
      title: '批量审核确认',
      icon: () => h(CheckOutlined, { style: { color: '#52c41a' } }),
      content: `确定要批量${statusText} ${selectedRowKeys.value.length} 个学习资料吗？`,
      okText: `确认${statusText}`,
      okType: auditStatus === 1 ? 'primary' : 'danger',
      cancelText: '取消',
      centered: true,
      onOk: () => executeBatchAudit(auditStatus, '批量审核通过')
    })
  }
}

// 显示批量拒绝原因输入框
const showBatchRejectModal = () => {
  let rejectReason = ''
  
  Modal.confirm({
    title: '批量拒绝审核',
    icon: () => h(ExclamationCircleOutlined, { style: { color: '#ff4d4f' } }),
    content: () => h('div', [
      h('p', `将批量拒绝 ${selectedRowKeys.value.length} 个学习资料，请输入拒绝原因:`),
      h('textarea', {
        class: 'ant-input',
        style: 'width: 100%; min-height: 80px; margin-top: 8px',
        placeholder: '请详细说明拒绝原因...',
        onInput: (e: any) => rejectReason = e.target.value
      })
    ]),
    okText: '确认批量拒绝',
    okType: 'danger',
    cancelText: '取消',
    centered: true,
    onOk: () => executeBatchAudit(2, rejectReason || '不符合要求')
  })
}

// 执行批量审核
const executeBatchAudit = async (auditStatus: number, auditReason: string) => {
  try {
    // 获取管理员ID
    const adminId = userStore.userInfo?.id
    if (!adminId) {
      message.error('获取管理员信息失败，请重新登录')
      return
    }

    await batchAuditLearningMaterial({
      adminId,
      batchMaterialAuditDTO: {
        materialIds: selectedRowKeys.value,
        auditStatus,
        auditReason
      }
    })
    
    const statusText = auditStatus === 1 ? '通过' : '拒绝'
    message.success(`批量${statusText}成功！共处理 ${selectedRowKeys.value.length} 项`)
    
    // 清空选择并刷新列表
    selectedRowKeys.value = []
    selectedRows.value = []
    await fetchMaterialList()
  } catch (error: any) {
    console.error('批量审核失败:', error)
    message.error('批量审核失败，请重试')
  }
}

const handleDelete = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    icon: () => h(ExclamationCircleOutlined, { style: { color: '#ff4d4f' } }),
    content: `确定要删除学习资料"${record.title}"吗？此操作不可恢复！`,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    centered: true,
    onOk: async () => {
      try {
        // 调用删除API
        console.log(record.id);
        
        await deleteLearningMaterial(record.id)
        
        message.success('删除成功!')
        
        // 重新加载数据
        await fetchMaterialList()
        
      
      } catch (error: any) {
       console.log(error);
       
        message.error(error.message || '删除失败，请重试')
      }
    },
    onCancel() {
     
    }
  })
}

// 页面挂载时获取数据
onMounted(() => {
  console.log('当前用户信息:', userStore.userInfo)
  fetchUploadStats()
  fetchAuditStats()
  fetchMaterialList()
})
</script>

<style scoped>
.file-manager {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 第一层：主要统计卡片 */
.main-stats {
  display: flex;
  gap: 20px;
  justify-content: space-between;
}

.stat-box {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.stat-box:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.upload-box {
  border-left: 4px solid #1890ff;
}

.audit-box {
  border-left: 4px solid #52c41a;
}

.pending-box {
  border-left: 4px solid #fa8c16;
}

.stat-icon {
  font-size: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background: rgba(24, 144, 255, 0.1);
  border-radius: 12px;
  color: #1890ff;
}

.audit-box .stat-icon {
  background: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

.pending-box .stat-icon {
  background: rgba(250, 140, 22, 0.1);
  color: #fa8c16;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  line-height: 1;
}


/* 响应式设计 */
@media (max-width: 768px) {
  .file-manager {
    padding: 16px;
    gap: 16px;
  }
  
  .main-stats {
    flex-direction: column;
    gap: 16px;
  }
  
  .stat-box {
    padding: 20px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 24px;
  }
  
  .stat-value {
    font-size: 24px;
  }
}

/* 学习资料管理样式 */
.material-management {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.material-header h2 {
  color: #333;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.material-header h2 .anticon {
  color: #1890ff;
}

.filter-section {
  background: #fafafa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

/* 批量操作样式 */
.batch-actions {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  padding: 12px 16px;
  margin-top: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.batch-actions span {
  color: #1890ff;
  font-weight: 500;
}

.batch-actions .ant-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons .ant-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  height: auto;
  font-size: 12px;
}

.material-list {
  background: transparent;
}

/* 表格样式优化 */
:deep(.ant-table) {
  border-radius: 8px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-tag) {
  font-weight: 500;
  border-radius: 4px;
  padding: 4px 8px;
}

/* 删除确认对话框样式 */
:deep(.ant-modal-confirm-body) {
  padding: 20px 0;
}

:deep(.ant-modal-confirm-title) {
  font-weight: 600;
  font-size: 16px;
}

:deep(.ant-modal-confirm-content) {
  margin-top: 12px;
  color: #666;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .filter-item {
    width: 100%;
  }
  
  .filter-item label {
    min-width: 80px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}

</style>
